import sys
import random
import matplotlib

matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QSizePolicy, QWidget
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import cv2

class MatplotlibWidget(FigureCanvas):
    def __init__(self,parent=None, width=5, height=4, dpi=100):
        # 配置中文显示
        plt.rcParams['font.family'] = ['SimHei']  # 用来正常显示中文标签
        plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

        # 不知道有什么用
        # plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
        # plt.margins(0, 0)

        # 第一步：创建一个创建Figure
        # self.fig = Figure(figsize=(width, height), dpi=dpi)  # 新建一个figure
        # self.fig = Figure()  # 新建一个figure
        # self.axes = self.fig.add_subplot(111)  # 建立一个子图，如果要建立复合图，可以在这里修改
        self.fig, self.axes = plt.subplots()

        # 第二步：在父类中激活Figure窗口
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        '''定义FigureCanvas的尺寸策略，这部分的意思是设置FigureCanvas，使之尽可能的向外填充空间。'''
        FigureCanvas.setSizePolicy(self,
                                   QSizePolicy.Expanding,
                                   QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

        #初始显示 空白图像
        self.data0 = np.full((512, 512, 3), (255,255,255), np.uint8)
        self.axes.imshow(self.data0,aspect='equal')
        self.axes.set_axis_off()  # 去坐标轴
        self.draw()

        #鼠标点击显示坐标
        # self.fig.canvas.mpl_connect('button_press_event', self.on_press)
        self.x = None
        self.y = None
        self.z = None
        self.flag = 0

        self.data = np.full((512, 512, 3), (255,255,255), np.uint8)
        self.data_init = np.full((512, 512, 3), (255,255,255), np.uint8)

    def get_data(self,select_data):
        self.data_init = select_data
        self.data = select_data

    def data_clip(self,min=None ,max=None):
        if min != None and max != None:
            self.data = np.clip(self.data_init, int(min), int(max))

    def get_label(self,label_data):
        self.label_data = label_data

    # def init_flag(self, select_flag):
    #     self.flag = select_flag

    # def on_press(self, event):
    #     print("my position:", event.button, event.xdata, event.ydata)
    #     print('flag=',self.flag)
    #     if self.flag != 0 :
    #         print(self.flag)
    #         if self.flag == 1:  # 正面
    #             self.start_data_plot(2,self.x,int(event.xdata),int(event.ydata))
    #             self.start_data_plot(3, self.x, int(event.xdata), int(event.ydata))
    #         # elif self.flag == 2:  # 侧面
    #         #     start_data_plot
    #         # else:  # 顶面
    #         #     start_data_plot


    # 绘制图像
    '''绘制静态图，可以在这里定义自己的绘图逻辑'''
    def start_data_plot(self,flag, x=None, y=None,z=None, lw=1, scale=0):
        if self.x == None and x == None:
            self.x = self.data.shape[0]//2
        else:
            if x !=None : self.x = x
        if self.y == None and y == None:
            self.y = self.data.shape[1]//2
        else:
            if y != None: self.y = y
        if self.z == None and z == None:
            self.z = self.data.shape[2]//2
        else:
            if z != None: self.z = z

        if self.x <= self.data.shape[0] and self.y <= self.data.shape[1] and self.z <= self.data.shape[2] :
            if flag == 1:#正面
                self.axes.clear()
                self.axes.imshow(self.data[self.x,:,:].transpose((1,0)),cmap='gray',aspect='equal')
                if scale!=0:
                    self.axes.set_ylim(int(self.data.shape[2]*(scale/400)),int(self.data.shape[2]*(1-scale/400)))
                    self.axes.set_xlim(int(self.data.shape[1]*(scale/400)),int(self.data.shape[1]*(1-scale/400)))
                else:
                    self.axes.invert_yaxis()
                self.axes.set_aspect(1.0/self.axes.get_data_ratio(), adjustable='box')
                # self.axes.invert_yaxis()
                self.axes.axhline(self.z, color='red', linestyle='--', lw=lw)
                self.axes.axvline(self.y, color='red', linestyle='--', lw=lw)
            elif flag == 2:#侧面
                self.axes.clear()
                self.axes.imshow(self.data[:,self.y,:].transpose((1,0)),cmap='gray',aspect='equal')
                if scale!=0:
                    self.axes.set_ylim(int(self.data.shape[2]*(scale/400)),int(self.data.shape[2]*(1-scale/400)))
                    self.axes.set_xlim(int(self.data.shape[0]*(scale/400)),int(self.data.shape[0]*(1-scale/400)))
                else:
                    self.axes.invert_yaxis()
                self.axes.set_aspect(1.0/self.axes.get_data_ratio(), adjustable='box')
                # self.axes.invert_yaxis()
                self.axes.axhline(self.z, color='red', linestyle='--', lw=lw)
                self.axes.axvline(self.x, color='red', linestyle='--', lw=lw)
            else:#顶面
                self.axes.clear()
                self.axes.imshow(self.data[:, :, self.z], cmap='gray', aspect='equal')
                if scale!=0:
                    self.axes.set_ylim(int(self.data.shape[0]*(scale/400)),int(self.data.shape[0]*(1-scale/400)))
                    self.axes.set_xlim(int(self.data.shape[1]*(scale/400)),int(self.data.shape[1]*(1-scale/400)))
                else:
                    self.axes.invert_yaxis()
                self.axes.set_aspect(1.0/self.axes.get_data_ratio(), adjustable='box')
                # self.axes.invert_yaxis()
                self.axes.axhline(self.x, color='red', linestyle='--', lw=lw)
                self.axes.axvline(self.y, color='red', linestyle='--', lw=lw)
        else:
            print(self.x,self.y,self.z,self.data.shape[0])

        # self.axes.set_axis_off()#去坐标轴
        self.draw()

    '''启动绘制动态图'''
    def start_clear_plot(self, *args, **kwargs):
        self.axes.clear()
        self.data = self.data0
        self.axes.imshow(self.data0, aspect='equal')
        self.axes.set_axis_off()  # 去坐标轴
        self.draw()

    '''动态图的绘图逻辑可以在这里修改'''

    def update_figure(self):
        self.axes.clear()# 每次绘图的时候不保留上一次绘图的结果
        self.draw()